package ntd.util.modular.data.util.handle;

import cn.hutool.core.util.HexUtil;
import com.LJ212Listen;
import com.ToolOpt;
import com.tool.ToolHex;
import ntd.block.server.bo.ComServerMsgBo;
import ntd.block.server.listen.ComAbsServerListen;
import ntd.util.UtilThreadPool;
import ntd.util.config.common.enums.data.EnumDataAcquisitionType;
import ntd.util.config.common.enums.data.EnumProtocolType;
import ntd.util.frame.server.util.UtilServer;
import ntd.util.frame.task.handle.fm.util.ToolFmData;
import ntd.util.modular.data.entity.DataAcquisitionRule;
import ntd.util.modular.data.util.handle.bo.ComRuleConfigBo;
import ntd.util.modular.data.util.handle.tool.Tool212;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ComDataGetRuleTcp212 implements ComDataGetRule {

    @Override
    public void close() {
    }

    @Override
    public Object handle(DataAcquisitionRule dataAcquisitionRule) {
        if (!dataAcquisitionRule.getEnumProtocolType().equals(EnumProtocolType.TCP_212)) {
            return "非TCP_212协议，不能执行该模块！";
        }
        if (dataAcquisitionRule.getEnumDataAcquisitionType().equals(EnumDataAcquisitionType.RULE_ACTIVE)) {

        }
        if (dataAcquisitionRule.getEnumDataAcquisitionType().equals(EnumDataAcquisitionType.RULE_PASSIVE)) {
            ComRuleConfigBo comRuleConfigBo = ComRuleConfigBo.transform(dataAcquisitionRule.getExtendJson());

            UtilServer.addListen(comRuleConfigBo.getServerAppId(), new ComAbsServerListen(){
                @Override
                public ComServerMsgBo onMsg(ComServerMsgBo comServerMsgBo) {
                    String key = comServerMsgBo.getKey();

                    List<String> strings = new ArrayList<>();
                    if (ToolHex.isHexNumber(comServerMsgBo.getMsg())) {
                        strings.addAll(LJ212Listen.cutMsg(key + "-hex", HexUtil.decodeHexStr(comServerMsgBo.getMsg())));
                    } else {
                        strings.addAll(LJ212Listen.cutMsg(key, comServerMsgBo.getMsg()));
                    }
                    for (String string : strings) {
                        LJ212Listen.handleMsg(comServerMsgBo, string);
                    }
                    return null;
                }

                @Override
                public void onClose(ComServerMsgBo comServerMsgBo) {
                    String mnByChannelId = Tool212.getMnByChannelId(comServerMsgBo.getKey());

                    // 设备离线
                    ToolOpt.OPT_T_DEVICE.offLine(mnByChannelId);

                    // 富铭，设备离线推送
                    if ("40289f5a7e94f892017e951800160000".equals(dataAcquisitionRule.getTenantId())) {
                        UtilThreadPool.run(() -> ToolFmData.OPT_FM_ON_LINE.offLine(mnByChannelId));
                    }
                }
            });
        }
        return "规则执行成功";
    }
}
